package com.hualan.servlet;

import com.alibaba.fastjson.JSON;
import com.hualan.bean.PanghuShopGoods;
import com.hualan.dao.PanghuGoodsDao;
import com.hualan.dao.PanghuGoodsDaoImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/goods/list")
public class PanghuGoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //1.获取前端 传递的分页信息 page和size
        String pageString = req.getParameter("pageNum");
        int pageNum = pageString == null? 1 : Integer.parseInt(pageString);
        String sizeString = req.getParameter("pageSize");
        int pageSize = sizeString == null ? 10 : Integer.parseInt(sizeString);
        //2.创建Map对象  用来给前端返回信息
        HashMap<String,Object> map = new HashMap<>();

        //3.查询数据总条数---增删改查来自Dao
        PanghuGoodsDao panghuGoodsDao = new PanghuGoodsDaoImpl();
        Long count = panghuGoodsDao.selectAllGoods();
        //将数量存储到map中
        map.put("total", count);

        //4.按照分页查询数据
        System.out.println(pageSize + "*********" + pageNum);
        List<PanghuShopGoods> goodsList = panghuGoodsDao.selectGoodsWithPage(pageNum, pageSize);
        //将数据以键值对  存储到map中
        map.put("list", goodsList);

        //5.设置code状态码 200成功 300失败； 以及message信息
        if(count > 0 && goodsList != null){
            map.put("code", 200);
            map.put("message", "成功");
        }else {
            map.put("code", 300);
            map.put("message", "失败");
        }
        //6.将数据源map  通过response返回给前端
        //问题？
        //.json是文件存储数据的一种格式！ 参考。txt  .word  .png  .html等  仅仅是一种文件格式！ 但是其内部遵循键值对{}和数组[]结构； 所以我们在进行网络数据输出都会使用此格式的数据进行传递！！！
        String jsonString = JSON.toJSONString(map);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
